package com.lagou.study.controller;

import com.lagou.study.pojo.LagouToken;
import com.lagou.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("register")
    public boolean register(String email, String password, String code){
        boolean result = userService.register(email, password, code);
        return result;
    }

    @PostMapping("isRegistered")
    public boolean isRegistered(String email){
        boolean result = userService.isRegistered(email);
        return result;
    }

    @PostMapping("login")
    public String login(HttpServletResponse response, String email, String password){
        LagouToken result = userService.login(email, password);
        if (result == null){
            return "";
        }else {
            Cookie cookie = new Cookie("token", result.getToken());
            response.addCookie(cookie);
            return result.getEmail();
        }
    }

    @PostMapping("info")
    public String info(String token){
        String email = userService.info(token);
        return email;
    }
}
